#include "logging.h"
#include "settings.h"

#include <QDate>

void Logging::initialize()
{
    qInstallMessageHandler(messageHandler);
    qSetMessagePattern(PATTERN);
}

void Logging::messageHandler(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
    const Settings &s = Settings::Singleton();
    int level = s.logLevel();

    QString message;
    switch (type) {
    case QtMsgType::QtInfoMsg:
        if (level < 1) {
            message = qFormatLogMessage(type, context, msg);
        }
        break;
    case QtMsgType::QtWarningMsg:
        if (level < 2) {
            message = qFormatLogMessage(type, context, msg);
        }
        break;
    case QtMsgType::QtCriticalMsg:
        if (level < 3) {
            message = qFormatLogMessage(type, context, msg);
        }
        break;
    case QtMsgType::QtFatalMsg:
        message = qFormatLogMessage(type, context, msg);
        break;
    default:
        break;
    }

    if (message.isEmpty()) return;

    QString name = s.logPath() + "/" + QDate::currentDate().toString("yyyyMMdd") + ".log";
    QString oldName = LOGFILE.fileName();
    if (name != oldName && (!oldName.isEmpty())) {
        if (LOGFILE.isOpen()) {
            LOGFILE.flush();
            LOGFILE.close();
        }
    }

    if (!LOGFILE.isOpen()) {
        LOGFILE.setFileName(name);
        if (!LOGFILE.open(QIODevice::WriteOnly | QIODevice::Append)) {
            qCritical() << "Log file open failed: " << LOGFILE.fileName() << ", reason: " << LOGFILE.errorString();
        }
    }
    LOGFILE.write(qPrintable(message));
    LOGFILE.write("\n");
    LOGFILE.flush();
}

QString Logging::PATTERN = "[%{time yyyyMMdd h:mm:ss.zzz t} %{if-debug}D%{endif}%{if-info}I%{endif}%{if-warning}W%{endif}%{if-critical}C%{endif}%{if-fatal}F%{endif}] - %{message}";
QFile Logging::LOGFILE;
